<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>放大镜插件</title>
		<style type = "text/css">
			*{
				margin:0;
				padding:0;
			}
			img{
				display:block;
				border:0;
			}
			.magnifier .left{
				width:300px;
				height:150px;
				float:left;
				border: 2px solid black;
				position: relative;
			}
			.magnifier .left img{
				width:300px;
				height:150px;
			}
			.magnifier .left .mask{
				width:100%;
				height:100%;
				position: absolute;
				top:0;
				left:0;
				background:green;
				opacity:0;
			}
			.magnifier .float{
				width:40px;
				height:40px;
				background-color:black;
				opacity: 0.5;
				position:absolute;
				left:0;
				top:0;
				display: none;
			}
			.magnifier .right{
				width:160px;
				height:160px;
				background-image: url(img/2.png);
				margin-left:100px;
				float:left;
				border:2px solid black;
				display: none;
			}
		</style>
		<script type = "text/javascript" src = "../jquery-3.4.1.js"></script>
	</head>
	<body>
		<div class="magnifier">
			<div class="left">
				<img src="img/1.png" alt="图片加载失败！">
				<div class="float"></div>
				<div class="mask"></div>
			</div>
			<div class="right"></div>
		</div>
		
		<script>
			(function($){
				$.fn.extend({
					magnifier:function(){
						this.each(function(index){
							var that = this;
							$(".left",this).on("mousemove",function(evt){
								var x = evt.offsetX;
								var y = evt.offsetY;
								var float = $(".float",this);
								 
								x = x - float.width() / 2;
								y = y - float.height() /2;
								
								if(x < 0 ){
									x = 0;
								}
								if(y < 0){
									y = 0;
								}
								if(x > $(this).width() - float.width()){
									x = $(this).width() - float.width();
								}
								if(y > $(this).height() - float.height()){
									y = $(this).height() - float.height();
								}
								float.css({
									left:x,
									top:y
								});
								
								$(".right",that).css({
									backgroundPosition:x*-4 + "px "+y*-4 + "px"
								})
							}).on("mouseover",function(){
								$(".left .float, .right",that).show();
							}).on("mouseout",function(){
								$(".left .float, .right",that).hide();
							})
						})
						return this;
					}
				})
			})(jQuery)
			
			$(".magnifier").magnifier();
		</script>
	</body>
</html>
